// This File is part of the "GmailNotifier2" Project
// 
// Copyright  2009 sometmes@gmail.com
// All rights reserved
// 
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;

namespace Notify2
{
    class SingleInstanceController:MarshalByRefObject
    {
        private SendMailForm sendMailForm;
        SynchronizationContext operation;

        public SingleInstanceController(SendMailForm sendMailForm)
        {
            this.AddFileDelegate = new SendOrPostCallback(this.AddFile);
            this.sendMailForm = sendMailForm;
            this.operation = SynchronizationContext.Current;
            if (this.operation == null)
                throw new ArgumentException("Must show form before accessing Synchronization context");
        }

        void CheckMainForm()
        {
            if (this.sendMailForm == null || this.sendMailForm.Visible == false)
            {
                this.sendMailForm = new SendMailForm();
            }
        }

        //private delegate void AddFileDelegate(string fileName);
        private SendOrPostCallback AddFileDelegate;

        private void AddFile(object fileName)
        {
            CheckMainForm();
            this.sendMailForm.Show();
            sendMailForm.AddFile(fileName as string);
        }

        public void AddFileAsync(string fileName)
        {
            this.operation.Post(this.AddFileDelegate, fileName);
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
